//
//  JZHProductDetailsViewController.m
//  极致荟
//
//  Created by hetao on 14-5-22.
//  Copyright (c) 2014年 mac. All rights reserved.
//

#import "JZHProductDetailsViewController.h"
#import "JZHShare.h"
#import "JZHHouViewController.h"
#import "ImageCache.h"
#import "JZHHuiFuTableViewCell.h"
#import "JZHHowLookMeViewController.h"
@interface JZHProductDetailsViewController ()
{
    NSString *imgPrefix;
}
- (IBAction)soping:(id)sender;
@property (weak, nonatomic) IBOutlet UIScrollView *scorll;

@end

@implementation JZHProductDetailsViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

///界面初始化构造方法
- (id)initCommdodity:(JZHCommodity *)commdity
{
    if(self)
    {
        self=[[JZHProductDetailsViewController alloc]init];
    }
    self.commodity=commdity;
    return self;
}
- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    [self.scorll setContentSize:CGSizeMake(0, 1150)];
    //设置左按钮
    
    UIButton *backBut=[[UIButton alloc]initWithFrame:CGRectMake(0, 0, 12, 20)];
    [backBut setBackgroundImage:[UIImage imageNamed:@"返回"] forState:UIControlStateNormal];
    ;
    
    [backBut addTarget:self action:@selector(back:) forControlEvents:UIControlEventTouchUpInside];
    [backBut.titleLabel setFont:[UIFont systemFontOfSize:14]];
    UIBarButtonItem *backBarButton=[[UIBarButtonItem alloc]initWithCustomView:backBut];
    [self.navigationItem setLeftBarButtonItem:backBarButton];
    
    //设置右按钮
    UIButton* leftButton=[[UIButton alloc]initWithFrame:CGRectMake(0, 0, 20, 20)];
    [leftButton setBackgroundImage:[UIImage imageNamed:@"share_button"] forState:UIControlStateNormal];
    [leftButton addTarget:self action:@selector(showce:) forControlEvents:UIControlEventTouchUpInside];
    
   //XX [self.navigationItem setRightBarButtonItem:[[UIBarButtonItem alloc] initWithCustomView:leftButton]];
    //设置导航视图title
    self.navigationItem.title=self.commodity.name;
   
    if(OSVersionIsAtLeastiOS7>=7.0)
    {
        self.automaticallyAdjustsScrollViewInsets=NO;
    }
    
    
    [self loadHttpData];
    
}

//返回
-(void)back:(id)sender
{
    if([UINavigationController miancerr]==1)
    {
        [UINavigationController Pop:self];
    }else
    {
        [self.navigationController popViewControllerAnimated:YES];
    }
    
}

- (void)loadHttpData
{
    //[MMProgressHUD showWithStatus:@"数据加载中..."];
    [self.scorll  setContentOffset:CGPointMake(0, 0) animated:NO];
    NSDictionary *dic=[[NSDictionary alloc]initWithObjectsAndKeys:[NSNumber numberWithInt:self.commodity.comid],@"contentId", nil];
    
    NSDictionary *dic2=[[NSDictionary alloc] initWithObjectsAndKeys:[NSNumber numberWithInt:self.commodity.comid],@"commentId",@"topic_content",@"commentType", nil];
    [HttpRequest httpRequestPost:JZHHTTPURL(@"comment/commentList") parameters:dic2 block:^(id data, HttpReturnCode rerurncode) {
        NSLog(@"%@",data);
        
        
        //取出评论数据
        
        NSMutableArray *muarr=[[NSMutableArray alloc]init];
        for(NSDictionary *comdic in [ [data objectForKey:@"data"]objectForKey:@"list"])
        {
            JZHReview *rev=[[JZHReview alloc]init];
            OtherUsers *ouser=[[OtherUsers alloc]init];
            OtherUsers *beouser;
            if([comdic objectForKey:@"beReplyUserId"]!=[NSNull null])
            {
                beouser=[[OtherUsers alloc] init];
                beouser.userId=[[comdic objectForKey:@"beReplyUserId"] intValue];
                if([comdic objectForKey:@"beReplyUserName"] ==[NSNull null])
                {
                    beouser.name=@"暂无";
                }else
                {
                    beouser.name=[comdic objectForKey:@"beReplyUserName"];
                }
            }else
            {
                beouser=nil;
            }
            
            ouser.userId=[[comdic objectForKey:@"userID"] intValue];
            ouser.username=[comdic objectForKey:@"userName"];
            ouser.userHeadImage=[imgPrefix stringByAppendingString:[comdic objectForKey:@"userAvatar"]];
            rev.recUser=ouser;
            rev.comment=[comdic objectForKey:@"content"];
            rev.revdate=[NSDate dateWithTimeIntervalSince1970:[[comdic objectForKey:@"addTime"] longLongValue]];
            rev.beReplyUser=beouser;
            [muarr addObject:rev];
            
            
        }
        self.commodity.rev=muarr;
        
        //评论请求完后在请求具体数据
        [HttpRequest httpRequestPost:JZHHTTPURL(@"topic/topicContentView") parameters:dic block:^(id data, HttpReturnCode rerurncode) {
            if(rerurncode==HTTPReturnCodeSuccess)
            {
                //[data objectForKey:@"data"];
                NSLog(@"%@",data);
                
                if(imgPrefix.length<3)
                {
                    imgPrefix=[[data objectForKey:@"data"] objectForKey:@"imgPrefix"];
                }
                // NSLog(@"%d",self.commodity.rev.count);
                [self.huifutable reloadData];
                
                //[MMProgressHUD dismiss];
                NSDictionary *datadic=[data objectForKey:@"data"];
                [self addImagescorll:[[datadic objectForKey:@"viewData"] objectForKey:@"image"]];
                
                
                NSString *str=@"";
                if([[[datadic objectForKey:@"viewData"] objectForKey:@"content"] isKindOfClass:[NSArray class]])
                {
                    for(NSString *conts in [[datadic objectForKey:@"viewData"] objectForKey:@"content"])
                    {
                        str=[str stringByAppendingString:conts];
                    }
                }else
                {
                     str=[[datadic objectForKey:@"viewData"] objectForKey:@"content"];
                }
               
                str=[str stringByReplacingOccurrencesOfString:@"<div>" withString:@""];
                str=[str stringByReplacingOccurrencesOfString:@"</div>" withString:@""];
                str=[str stringByReplacingOccurrencesOfString:@"&it;" withString:@""];
                str=[str stringByReplacingOccurrencesOfString:@"&gt;" withString:@""];
                str=[str stringByReplacingOccurrencesOfString:@"/div" withString:@""];
                str=[str stringByReplacingOccurrencesOfString:@"&lt;" withString:@""];
                str=[str stringByReplacingOccurrencesOfString:@"div" withString:@""];
                [self.view1text setText:str];
                self.pm.text=[[datadic objectForKey:@"viewData"] objectForKey:@"brandName"];
                self.brand.text=self.commodity.name;
                self.meony.text=[[datadic objectForKey:@"viewData"] objectForKey:@"price"];
                self.navigationItem.title=[[datadic objectForKey:@"viewData"] objectForKey:@"title"];
                self.commodity.comtype=[[[datadic objectForKey:@"viewData"] objectForKey:@"type"] intValue];
                [self aoutviewframUserhead:[[datadic objectForKey:@"favoriteData"] objectForKey:@"list"] xsp:[datadic objectForKey:@"likeData"]];
                [self.brand sizeToFit];
            }else
            {
                [MMProgressHUD showInformationWithTips:@"加载失败！"];
            }
            
        }];

    }];
   
}
///根据数据内容自动调节页面布局
- (void)aoutviewframUserhead:(NSArray *)uarr xsp:(NSArray *)xarr
{
 CGSize  size=[self.view1text sizeThatFits:CGSizeMake(self.view1text.frame.size.width, 0)];
    NSLog(@"%f",size.height);
    //适配商品简介框高度
    [self.view1text setFrame:CGRectMake(self.view1text.frame.origin.x, self.view1text.frame.origin.y, self.view1text.frame.size.width, size.height)];
    //适配第一节VIEW高度 位置不变
    [self.view1 setFrame:CGRectMake(self.view1.frame.origin.x, self.view1.frame.origin.y, self.view1.frame.size.width, self.view1text.frame.size.height+26)];
     //适配第二节VIEW高度和位置
    [self addhaedimage:uarr];
    [self.view2 setFrame:CGRectMake(self.view2.frame.origin.x, self.view1.frame.origin.y+self.view1.frame.size.height, self.view2.frame.size.width, self.view2imageview.frame.size.height+self.huifutable.frame.size.height+40)];
    ///适配第三节VIEW高度和位置
    [self addspimage:xarr];
    [self.view3 setFrame:CGRectMake(self.view3.frame.origin.x, self.view2.frame.origin.y+self.view2.frame.size.height, self.view3.frame.size.width, 70+self.view3imageview.frame.size.height+self.view3but.frame.size.height)];
    [self.scorll setContentSize:CGSizeMake(0, self.view1.frame.size.height+self.view2.frame.size.height+self.view3.frame.size.height+self.view1.frame.origin.y)];
}

///添加喜欢客户的头像并设置头像父容器高度
- (void)addhaedimage:(NSArray *)arr
{
    if(arr.count!=0)
    {
        UITapGestureRecognizer *tap=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(cklik:)];
        [self.view2imageview addGestureRecognizer:tap];
        self.likelable.hidden=NO;
    }
    if(arr.count<1)
    {
        self.likelable.hidden=YES;
    }else
    {
        self.likelable.text=[NSString stringWithFormat:@"有%d人喜欢",arr.count];
    }
    
    int i=1;
    for(int row=0;row<2;row++)
    {
        for(int l=0;l<7;l++)
        {
            UIImageView *image=[[UIImageView alloc]initWithFrame:CGRectMake(l*35+(l+1)*5, row*5+row*35, 35, 35)];
            if(arr.count>0)
            {
                NSString *path=[imgPrefix stringByAppendingString:[[arr objectAtIndex:i-1] objectForKey:@"userAvatar"]];
                [ImageCache imageUrl:path UiImageview:image];
                [self.view2imageview addSubview:image];
            }
           
            i++;
            if(i>arr.count)
            {
               if(arr.count==0)
               {
                   //设置头像父容器高度
                   [self.view2imageview setFrame:CGRectMake(self.view2imageview.frame.origin.x, self.view2imageview.frame.origin.y, self.view2imageview.frame.size.width, 0)];
               }else
               {
                   //设置头像父容器高度
                   [self.view2imageview setFrame:CGRectMake(self.view2imageview.frame.origin.x, self.view2imageview.frame.origin.y, self.view2imageview.frame.size.width, (row+1)*35+row*5)];
               }
               
                //设置评论table位置和高度
                if([self.huifutable numberOfRowsInSection:0]>=2)
                {
                    [self.huifutable setFrame:CGRectMake(self.huifutable.frame.origin.x, self.view2imageview.frame.origin.y+self.view2imageview.frame.size.height, self.huifutable.frame.size.width, 130)];
                }else if([self.huifutable numberOfRowsInSection:0]!=0)
                {
                    [self.huifutable setFrame:CGRectMake(self.huifutable.frame.origin.x, self.view2imageview.frame.origin.y+self.view2imageview.frame.size.height, self.huifutable.frame.size.width, 60)];
                }else
                {
                     [self.huifutable setFrame:CGRectMake(self.huifutable.frame.origin.x, self.view2imageview.frame.origin.y+self.view2imageview.frame.size.height, self.huifutable.frame.size.width, 0)];
                }
                
                return ;
            }
        }
    }
    
    
}

- (void)cklik:(UITapGestureRecognizer *)tap
{
    [self.navigationController pushViewController:[[JZHHowLookMeViewController alloc] initType:2 activit:self.commodity] animated:YES];
}
- (IBAction)xihuan:(UIButton *)sender
{
    NSDictionary *dic=[[NSDictionary alloc]initWithObjectsAndKeys:[NSNumber numberWithInt:[User defuceUser].userId],@"userId", [NSNumber numberWithInt:self.commodity.comid],@"favoriteId",@"topic_content",@"favoriteType", nil];
    [HttpRequest httpRequestPost:JZHHTTPURL(@"favorite/addFavorite") parameters:dic block:^(id data, HttpReturnCode rerurncode) {
        
        if(rerurncode==0)
        {
           [UIView animateWithDuration:0.3 animations:^{
               [sender setFrame:CGRectMake(sender.frame.origin.x-5, sender.frame.origin.y-5, sender.frame.size.width+5, sender.frame.size.height+5)];
               
           } completion:^(BOOL finished) {
               [UIView animateWithDuration:.3 animations:^{
                     [sender setFrame:CGRectMake(sender.frame.origin.x+5, sender.frame.origin.y+5, sender.frame.size.width-5, sender.frame.size.height-5)];
               }];
           }];
        }else if(rerurncode==-4){
            [UIView animateWithDuration:0.3 animations:^{
                [sender setFrame:CGRectMake(sender.frame.origin.x-5, sender.frame.origin.y-5, sender.frame.size.width+5, sender.frame.size.height+5)];
            } completion:^(BOOL finished) {
                [UIView animateWithDuration:.3 animations:^{
                    [sender setFrame:CGRectMake(sender.frame.origin.x+5, sender.frame.origin.y+5, sender.frame.size.width-5, sender.frame.size.height-5)];
                }];
            }];

           
        }else
        {
        }
        
    }];
}

///添加推荐商品图片
- (void)addspimage:(NSArray *)arr
{
    
    int i=1;
    for(int row=0;row<3;row++)
    {
        for(int l=0;l<3;l++)
        {
            if(arr.count>0)
            {
                UIImageView *image=[[UIImageView alloc]initWithFrame:CGRectMake(l*80+(l+1)*10, row*70+row*8, 80, 70)];
                [ImageCache imageUrl:[imgPrefix stringByAppendingString:[arr[i-1] objectForKey:@"cover_image"]] UiImageview:image];
                image.tag=40+[[arr[i-1] objectForKey:@"id"] intValue];
                UITapGestureRecognizer *tap=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapcom:)];
                [image addGestureRecognizer:tap];
                [image setUserInteractionEnabled:YES];
                [self.view3imageview addSubview:image];
            }else
            {
                self.xstj.hidden=YES;
            }
           
            i++;
            if(i>arr.count)
            {
                [self.view3imageview setFrame:CGRectMake(self.view3imageview.frame.origin.x, self.view3imageview.frame.origin.y, self.view3imageview.frame.size.width, (row+1)*70+row*8)];
                [self.view3but setFrame:CGRectMake(self.view3but.frame.origin.x, self.view3imageview.frame.origin.y+self.view3imageview.frame.size.height+10, self.view3but.frame.size.width, self.view3but.frame.size.height)];
                return;
            }
        }
    }
    
}
- (void)addImagescorll:(NSArray *)arr
{
    for(UIView *viewsd in self.imagescorll.subviews)
    {
        [viewsd removeFromSuperview];
    }
    [self.imagescorll setContentSize:CGSizeMake(320*arr.count, 0)];
    [self.page setNumberOfPages:arr.count];
    int index=0;
    for(NSString *str in arr)
    {
        UIImageView *image=[[UIImageView alloc]initWithFrame:CGRectMake(320*index, 0, self.imagescorll.frame.size.width, self.imagescorll.frame.size.height)];
        NSLog(@"%@",[imgPrefix stringByAppendingString:str ]);
        [ImageCache imageUrl:[imgPrefix stringByAppendingString:str ]UiImageview:image];
        [self.imagescorll addSubview:image];
        index++;
    }
}

- (void)tapcom:(UITapGestureRecognizer *)tap
{
    self.commodity.comid=tap.view.tag-40;
    for(UIView * v in [self.view2imageview subviews])
    {
        [v removeFromSuperview];
    }
    
    [self loadHttpData];
}
- (void)showce:(UIButton *)but
{
    JZHShare *share=[[NSBundle mainBundle]loadNibNamed:@"JZHShare" owner:self options:nil][0];
    [share show:1 viewcontroller:self];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)puspin:(id)sender
{
    [self.navigationController pushViewController:[[JZHHouViewController alloc]initId:self.commodity type:0] animated:YES];
}
#pragma mark-------TableView代理----------
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section;

{
    NSLog(@"%d",self.commodity.rev.count);
    return self.commodity.rev.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    JZHHuiFuTableViewCell *ce=[[NSBundle mainBundle] loadNibNamed:@"JZHHuiFuTableViewCell" owner:self options:nil][0];
    return [ce addCellData:self.commodity.rev[indexPath.row] viewconteroller:self isHuiFu:YES];
    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *pengyoucell=@"PengyouCell";
    
    JZHHuiFuTableViewCell *cell=[tableView dequeueReusableHeaderFooterViewWithIdentifier:pengyoucell];
    if(!cell)
    {
        cell=[[NSBundle mainBundle]loadNibNamed:@"JZHHuiFuTableViewCell" owner:self options:nil][0];
    }
    [cell addCellData:self.commodity.rev[indexPath.row] viewconteroller:self isHuiFu:YES];
    return cell;
    
}


#pragma mark----scorllview delete-----
- (void)scrollViewDidScroll:(UIScrollView *)scrollView;
{
    
    CGFloat x=scrollView.contentOffset.x/320;
    if(fmod (x,1 )==0)
    {
        [_page setCurrentPage:x];
    }
    
}

- (IBAction)soping:(id)sender
{
    [[[UIAlertView alloc] initWithTitle:@"提示" message:@"当前功能即将开放，请等待" delegate:nil cancelButtonTitle:@"好" otherButtonTitles:nil, nil] show];
}
@end
